package unit18.exec;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Scanner;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSetMetaData;
import com.mysql.jdbc.Statement;

public class ExecSQL {
	public static void main(String[] args) throws IOException {
		try {
			Scanner in=args.length==0?new Scanner(System.in):new Scanner(Paths.get(args[0]));
			try(Connection conn=getConnection()){
				Statement stmt=(Statement) conn.createStatement();
				
				while(true){
					if(args.length==0)
						System.out.println("Enter command to EXIT	to exit:");
					if(!in.hasNextLine())
						return ;
					String line=in.nextLine();
					if("EXIT".equalsIgnoreCase(line)){
						return;
					}
					if(";".endsWith(line.trim())){
						line=line.trim();
						line=line.substring(0,line.length()-1);
					}
					try {
						boolean isResult=stmt.execute(line);
						if(isResult){
							ResultSet 	rs=stmt.getResultSet();
							showResultSet(rs);
						}else{
							int updateCount=stmt.getUpdateCount();
							System.out.println(updateCount+" rows updated.");
						}
					} catch (SQLException e) {
						// TODO: handle exception
						for(Throwable t:e){
							t.printStackTrace();
						}
					}
				}
			}
		} catch (SQLException ex) {
			// TODO: handle exception
			for(Throwable tt:ex){
				tt.printStackTrace();
			}
		}
	}

	private static void showResultSet(ResultSet rs) throws SQLException {
		// TODO Auto-generated method stub
		ResultSetMetaData resultSetMetaData=(ResultSetMetaData) rs.getMetaData();
		int columCount=resultSetMetaData.getColumnCount();
		
		for(int x=1;x<columCount;x++){
			if(x>1)
				System.out.print(", ");
				System.out.print(resultSetMetaData.getColumnLabel(x));
		}
		System.out.println();
		while(rs.next()){
			for(int x=1;x<=columCount;x++){
				if(x>1)
					System.out.print(", ");
				System.out.print(rs.getString(x));
			}
			System.out.println();
		}
	}
	
	private static Connection getConnection() throws SQLException, IOException {
		// TODO Auto-generated method stub
		Properties p=new Properties();
		try(InputStream in=Files.newInputStream(Paths.get("src\\unit18\\test\\jdbc.properties"))){
			p.load(in);
		}
		String drivers=p.getProperty("jdbc.drivers");
		if(drivers!=null)
			System.setProperty("jdbc.drivers",drivers);
		String url=p.getProperty("jdbc.url");
		String username=p.getProperty("jdbc.username");
		String password=p.getProperty("jdbc.password");
		return (Connection) DriverManager.getConnection(url,username,password);
	}
}
